package com.andatsoft.laisim.dialog;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.theme.ThemeManager;
import com.andatsoft.laisim.utils.Common;
import com.andatsoft.laisim.utils.ToastMessage;
import com.andatsoft.laisim.view.WPProgressBar;

public class LyricsGettingDialog extends Activity {

	private char[] firstGroup = new char[] { 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'Ấ', 'Ầ',
			'Ẩ', 'Ẫ', 'Ậ', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ', 'Ặ',
			'á', 'à', 'ả', 'ã', 'ạ', 'â', 'ă', 'Á', 'À', 'Ả', 'Ã', 'Ạ', 'Â',
			'Ă' };
	private char[] secondGroup = new char[] { 'ế', 'ề', 'ể', 'ễ', 'ệ', 'Ế',
			'Ề', 'Ể', 'Ễ', 'Ệ', 'é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'É', 'È', 'Ẻ',
			'Ẽ', 'Ẹ', 'Ê' };
	private char[] thirdGroup = new char[] { 'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'Ố', 'Ồ',
			'Ổ', 'Ô', 'Ộ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ',
			'ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ơ', 'Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô',
			'Ơ' };
	private char[] fourthGroup = new char[] { 'í', 'ì', 'ỉ', 'ĩ', 'ị', 'Í',
			'Ì', 'Ỉ', 'Ĩ', 'Ị' };
	private char[] fivethGroup = new char[] { 'ứ', 'ừ', 'ử', 'ữ', 'ự', 'Ứ',
			'Ừ', 'Ử', 'Ữ', 'Ự', 'ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'Ú', 'Ù', 'Ủ',
			'Ũ', 'Ụ', 'Ư' };
	private char[] sixthGroup = new char[] { 'ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'Ý', 'Ỳ',
			'Ỷ', 'Ỹ', 'Ỵ' };
	private char[] seventhGroup = new char[] { 'đ', 'Đ' };
	private char[] eightGroup = new char[] { '\'', '"', '~', '!', '#', '$',
			'%', '^', ':', ';', '<', '>', '?', '-' };

	private class SongItem {
		String songTitle;
		String artist;
		String url;
	}

	private ListView mListView;
	private List<SongItem> mSongList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		getWindow().setBackgroundDrawable(
				new ColorDrawable(ThemeManager.getSelectedTheme()
						.getDialogBackgroundColor()));
		setContentView(R.layout.dialog_lyrics_getting);
		mListView = (ListView) findViewById(R.id.dialog_listview);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				Intent i = new Intent();
				i.putExtra(Common.RESULT_INTENT_FOR_LYRICS_FRAGMENT,
						mSongList.get(pos).url);
				LyricsGettingDialog.this.setResult(
						Common.RESULT_CODE_FOR_LYRICS_FRAGMENT, i);
				finish();
			}
		});
		((TextView) findViewById(R.id.tv_title_list_dialog))
				.setTextColor(ThemeManager.getSelectedTheme()
						.getDialogTextColor());
		String songT = getIntent().getStringExtra(Common.SONG_TITLE_INTENT);
		new LyricsFinder().execute(songT);
	}

	private String encodeUrl(String src) {

		char[] temp = src.toCharArray();
		StringBuilder re = new StringBuilder();
		for (int i = 0; i < temp.length; i++) {
			char val = temp[i];
			if (val == 32)
				val = '+';
			if ((val >= 0 && val <= 9) || (val >= 65 && val <= 90)
					|| (val >= 97 && val <= 122) || (val == '+')) {
				re.append(val);
			} else {
				char newVal = convertVn(val);
				if (newVal != 123)
					re.append(convertVn(val));
			}
		}
		return re.toString();
	}

	private char convertVn(char c) {
		// check in group 1
		for (int i = 0; i < firstGroup.length; i++)
			if (firstGroup[i] == c)
				return 'a';
		// check in group 2
		for (int i = 0; i < secondGroup.length; i++)
			if (secondGroup[i] == c)
				return 'e';
		// check in group 3
		for (int i = 0; i < thirdGroup.length; i++)
			if (thirdGroup[i] == c)
				return 'o';
		// check in group 4
		for (int i = 0; i < fourthGroup.length; i++)
			if (fourthGroup[i] == c)
				return 'i';
		// check in group 5
		for (int i = 0; i < fivethGroup.length; i++)
			if (fivethGroup[i] == c)
				return 'u';
		// check in group 6
		for (int i = 0; i < sixthGroup.length; i++)
			if (sixthGroup[i] == c)
				return 'y';
		// check in group 7
		for (int i = 0; i < seventhGroup.length; i++)
			if (seventhGroup[i] == c)
				return 'd';
		// check in group 8
		for (int i = 0; i < eightGroup.length; i++)
			if (eightGroup[i] == c)
				return 123;
		return '_';

	}

	private String decoderHtml(String src) {
		if (src.contains("&amp;"))
			src = src.replace("&amp;", "&");
		if (src.contains("&#039;"))
			src = src.replace("&#039;", "'");
		return src;
	}

	private SongItem getSongItem(TagNode aNode) {
		if (aNode == null)
			return null;
		SongItem song = new SongItem();
		setSongTitleAndArtist(song, aNode.getAttributeByName("title"));
		song.url = "http://mp3.zing.vn" + aNode.getAttributeByName("href");
		return song;
	}

	private void setSongTitleAndArtist(SongItem s, String src) {
		String[] str = src.split(" - ");
		if (str == null || str.length < 2)
			return;
		s.songTitle = decoderHtml(str[0]);
		s.artist = decoderHtml(str[1]);
	}

	class LyricsFinder extends AsyncTask<String, Void, Integer> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			((WPProgressBar) findViewById(R.id.progressbar_list_dialog))
					.setVisibility(View.VISIBLE);
		}

		@Override
		protected Integer doInBackground(String... params) {
			String songTitle = encodeUrl(params[0]);
			mSongList = new ArrayList<LyricsGettingDialog.SongItem>();
			try {
				URL url = new URL("http://mp3.zing.vn/tim-kiem/bai-hat.html?q="
						+ songTitle + "&filter=4");
				HtmlCleaner html = new HtmlCleaner();
				CleanerProperties props = html.getProperties();
				props.setAllowHtmlInsideAttributes(true);
				props.setAllowMultiWordAttributes(true);
				props.setRecognizeUnicodeChars(true);
				props.setOmitComments(true);

				TagNode node = html.clean(url);
				String xPathExpression = "//div[@class='first-search-song']//h3";

				// Get the first song
				Object[] obj = node.evaluateXPath(xPathExpression);
				if (obj.length <= 0)
					return null;
				TagNode[] firstNode = ((TagNode) obj[0]).getElementsByName("a",
						false);
				// Add the first song
				mSongList.add(getSongItem(firstNode[0]));

				// Get 9 item more.
				xPathExpression = "//div[@class='content-item ie-fix']//h3";
				obj = node.evaluateXPath(xPathExpression);

				TagNode songNode;
				int max = obj.length >= 9 ? 9 : obj.length;
				for (int i = 0; i < max; i++) {
					firstNode = ((TagNode) obj[i])
							.getElementsByName("a", false);
					songNode = (TagNode) firstNode[0];
					mSongList.add(getSongItem(songNode));
				}

			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
				return -1;
			} catch (XPatherException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return 0;
		}

		@Override
		protected void onPostExecute(Integer result) {
			mListView.setAdapter(new MyAdapter(getApplicationContext()));
			((WPProgressBar) findViewById(R.id.progressbar_list_dialog))
					.setVisibility(View.INVISIBLE);
			if (result == null) {
				new ToastMessage(getApplicationContext())
						.showLongMessage(getString(R.string.toast_no_song_lyrics_found));
			} else if (result.equals(-1)) {
				new ToastMessage(getApplicationContext())
						.showLongMessage(getString(R.string.toast_connection_timeout));
			}
		}
	}

	private class MyAdapter extends ArrayAdapter<SongItem> {

		public MyAdapter(Context context) {
			super(context, 0);
		}

		@Override
		public int getCount() {
			return mSongList.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				v = getLayoutInflater().inflate(
						R.layout.pager_main_song_list_item, parent, false);
				TextView tv = (TextView) v
						.findViewById(R.id.tv_pager_main_song_list_item_title);
				tv.setTextColor(ThemeManager.getSelectedTheme()
						.getMPLNormalTitleColor());
				tv.setText(mSongList.get(position).songTitle);
				tv.setTextSize(20f);
				tv = (TextView) v
						.findViewById(R.id.tv_pager_main_song_list_item_artist);
				tv.setTextColor(ThemeManager.getSelectedTheme()
						.getMPLNormalArtistColor());
				tv.setText(mSongList.get(position).artist);
			}
			return v;
		}

	}

}
